package Day012_多线程2.demo03_并发包;

import java.util.concurrent.CountDownLatch;

/**
 * @author zhangyan
 * @date 2020/4/30 14:21
 */
/*
    CountDownLatch: 允许一个或多个线程等待其他线程完成操作。

        例如：线程1要执行打印：A和C，线程2要执行打印：B，但线程1在打印A后，要线程2打印B之后才能打印C，所
        以：线程1在打印A后，必须等待线程2打印完B之后才能继续执行。
        CountDownLatch构造方法:
                            public CountDownLatch(int count)  初始化一个指定计数器的CountDownLatch对象

        CountDownLatch重要方法:
                            public void await() throws InterruptedException  让当前线程等待
                            public void countDown()  计数器进行减1
 */
public class demo05_CountDownLatch {
    public static void main(String[] args) {

        //创建对象
        CountDownLatch cdl = new CountDownLatch(1);

        MyRunnableA mrA = new MyRunnableA(cdl);
        Thread t1 = new Thread(mrA);
        t1.start();

        MyRunnableB mrB = new MyRunnableB(cdl);
        Thread t2 = new Thread(mrB);
        t2.start();

        // ACB ABC BAC
        // 如果要求打印 ABC,打印完A暂停,等待线程B执行
    }
}

class MyRunnableA implements Runnable {
    //构造成员变量
     CountDownLatch cdl;

    public MyRunnableA(CountDownLatch cdl) {
        this.cdl = cdl;
    }

    @Override
    public void run() {
        System.out.println("A");
        /*//睡眠暂停
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/

        try {
            cdl.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("C");
    }
}

class MyRunnableB implements Runnable {
    CountDownLatch cdl;
    public MyRunnableB(CountDownLatch cdl){
        this.cdl = cdl;
    }
    @Override
    public void run() {
        System.out.println("B");
        cdl.countDown();//计数器减一
    }
}